import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'oy-r-autio-play',
  templateUrl: './r-autio-play.component.html',
  styleUrls: ['./r-autio-play.component.scss']
})
/**
 * 描述：音乐播放器ts控制
 * 公司：xxx有限公司
 * 版权：xxx2020
 * 作者：oyjl
 * 时间：2020-04-16 12:27:44
 */
export class RAutioPlayComponent implements OnInit, AfterViewInit {

  public audioSource: any; // 音乐源
  public index: number; // 当前播放的音乐索引
  public lrcJson: number; // 格式json
  public currentLrc: string; // 当前歌词
  public currentTime: number; // 当前时间
  public currentVolume: number; // 当前音量
  public oldVolume: number; // 保留旧的音量，便于打开声音恢复原状
  public listShow: boolean; // 音乐列表显示
  public ti: any; // 全局控制时间对象
  public isCycle: boolean; // 是否循环播放
  public playSort: string; // 播放顺序，order为顺序播放，random为随机播放，cycle为单曲循环
  public isLoadAnimation: boolean; // 是否加载动画
  @ViewChild('audioMain') audioMain;
  @ViewChild('audioContainer') audioContainer;
  @ViewChild('audioPlayBtn') audioPlayBtn;
  @ViewChild('audioVolumeBtn') audioVolumeBtn;
  @Input() audioList: Array<object>; // 音乐列表
  constructor(public http: HttpClient, public el: ElementRef) { }

  ngOnInit() {
    if (this.audioList && this.audioList.length > 0) {
      this.index = 0;
      this.audioSource = this.audioList[this.index];
      this.setSelectedAudioCss(this.index);
      this.currentLrc = this.audioSource.name;
      this.listShow = false;
    }
    this.isCycle = true;
    this.playSort = 'order';
    this.isLoadAnimation = false;
  }

  ngAfterViewInit(): void {
    if (this.audioContainer) {
      this.currentVolume = 50;
      this.audioContainer.nativeElement.volume = 0.5;
      this.oldVolume = 0.5;
      this.audioPlay(this.audioContainer.nativeElement, this.audioPlayBtn.nativeElement); // 默认播放
    }
  }

  /**
   * 描述：秒钟转换成时分秒格式
   * 作者：oyjl
   * 时间：2020-04-15 11:40:31
   */
  public secondSwitchTime(time) {
    if (!isNaN(time)) {
      let hour;
      let minute;
      let second;
      hour = Math.floor(time / 3600);
      minute = Math.floor((time % 3600) / 60);
      second = Math.floor(time % 3600 % 60);
      if (hour < 10) {
        hour = '0' + hour;
      }
      if (minute < 10) {
        minute = '0' + minute;
      }
      if (second < 10) {
        second = '0' + second;
      }
      let tempTime;
      if (hour === '00') {
        tempTime = minute + ':' + second;
      } else {
        tempTime = hour + ':' + minute + ':' + second;
      }
      if (this.audioContainer && time < this.audioContainer.nativeElement.duration && this.lrcJson && this.lrcJson[tempTime]) {
        this.currentLrc = this.lrcJson && this.lrcJson[tempTime];
      }
      return tempTime;
    }
  }

  /**
   * 描述：音频文件播放/暂停控制
   * 作者：oyjl
   * 时间：2020-04-15 12:05:13
   */
  public audioPlay(audioContainer, audioPlayBtn) {
    if (this.audioList && this.audioList.length > 0) {
      audioPlayBtn.classList.toggle('fa-play');
      audioPlayBtn.classList.toggle('fa-pause');
      this.currentLrc = '';
      if (audioPlayBtn.classList.contains('fa-pause')) {
        this.isCycle = true;
        audioPlayBtn.title = '暂停';
        this.setSelectedAudioCss(this.index);
        this.lrcHandle();
        this.cyclePlay();
      } else if (audioPlayBtn.classList.contains('fa-play')) {
        this.isCycle = false;
        audioPlayBtn.title = '播放';
      } else { }
    }
  }

  /**
   * 描述：上一曲控制
   * 作者：oyjl
   * 时间：2020-04-15 14:03:14
   */
  public audioBackward(audioContainer, audioPlayBtn) {
    if (this.audioList && this.audioList.length > 0) {
      if (this.index > 0) {
        --this.index;
      } else {
        this.index = this.audioList.length - 1;
      }
      this.currentLrc = '';
      this.audioSource = this.audioList[this.index];
      this.lrcHandle();
      this.isCycle = true;
      this.setSelectedAudioCss(this.index);
      this.cyclePlay();
    }
  }

  /**
   * 描述：下一曲控制
   * 作者：oyjl
   * 时间：2020-04-15 14:03:27
   */
  public audioForward(audioContainer, audioPlayBtn) {
    if (this.audioList && this.audioList.length > 0) {
      if (this.index < (this.audioList.length - 1)) {
        ++this.index;
      } else {
        this.index = 0;
      }
      this.currentLrc = '';
      this.audioSource = this.audioList[this.index];
      this.lrcHandle();
      this.isCycle = true;
      this.setSelectedAudioCss(this.index);
      this.cyclePlay();
    }
  }

  /**
   * 描述：获取歌词json数据
   * 作者：oyjl
   * 时间：2020-04-15 15:57:52
   */
  public lrcHandle() {
    this.http.get(this.audioSource.lrc).subscribe((res: any) => {
      this.lrcJson = res;
    });
  }

  /**
   * 描述：音量设置
   * 作者：oyjl
   * 时间：2020-04-15 16:01:15
   */
  public volumeSet(event, audioContainer) {
    this.oldVolume = this.currentVolume / 100;
    if (event) {
      this.currentVolume = event.value;
      audioContainer.volume = event.value / 100;
      if (event.value > 0) {
        this.audioVolumeBtn.nativeElement.classList.add('fa-volume-up');
        this.audioVolumeBtn.nativeElement.classList.remove('fa-volume-off');
      } else {
        this.audioVolumeBtn.nativeElement.classList.remove('fa-volume-up');
        this.audioVolumeBtn.nativeElement.classList.add('fa-volume-off');
      }
    }
  }

  /**
   * 描述：静音/打开音量
   * 作者：oyjl
   * 时间：2020-04-15 16:29:44
   */
  public volumeMute(audioContainer, audioVolumeBtn) {
    audioVolumeBtn.classList.toggle('fa-volume-up');
    audioVolumeBtn.classList.toggle('fa-volume-off');
    if (audioVolumeBtn.classList.contains('fa-volume-off')) {
      this.currentVolume = 0;
      audioContainer.volume = 0;
    } else if (audioVolumeBtn.classList.contains('fa-volume-up')) {
      this.currentVolume = this.oldVolume * 100;
      audioContainer.volume = this.oldVolume;
    } else { }
  }

  /**
   * 描述：拖动滑块设置音频播放时间
   * 作者：oyjl
   * 时间：2020-04-15 16:59:42
   */
  public scheduleSet(event, audioContainer) {
    audioContainer.currentTime = event.value;
  }
  /**
   * 描述：播放顺序
   * 作者：oyjl
   * 时间：2020-04-15 16:43:25
   */
  public audioOrder(audioOrderBtn) {
    // 顺序，随机，单曲图标循环处理
    if (audioOrderBtn.classList.contains('fa-exchange')) {
      audioOrderBtn.classList.remove('fa-exchange');
      audioOrderBtn.classList.add('fa-random');
    } else if (audioOrderBtn.classList.contains('fa-random')) {
      audioOrderBtn.classList.remove('fa-random');
      audioOrderBtn.classList.add('fa-refresh');
    } else if (audioOrderBtn.classList.contains('fa-refresh')) {
      audioOrderBtn.classList.remove('fa-refresh');
      audioOrderBtn.classList.add('fa-exchange');
    } else { }
    // 3中播放顺序标志物以及title处理
    if (audioOrderBtn.classList.contains('fa-exchange')) {
      this.playSort = 'order';
      audioOrderBtn.title = '顺序播放';
    } else if (audioOrderBtn.classList.contains('fa-random')) {
      this.playSort = 'random';
      audioOrderBtn.title = '随机播放';
    } else if (audioOrderBtn.classList.contains('fa-refresh')) {
      this.playSort = 'cycle';
      audioOrderBtn.title = '单曲循环';
    } else { }
  }

  /**
   * 描述：选择列表中的音频文件
   * 作者：oyjl
   * 时间：2020-04-16 08:21:21
   */
  public audioChoose(i, audioListItem) {
    this.index = i;
    this.audioSource = this.audioList[i];
    this.el.nativeElement.querySelectorAll('tr').forEach(element => {
      element.classList.remove('active');
    });
    audioListItem.classList.add('active');
  }

  /**
   * 描述：设置选中的样式
   * 作者：oyjl
   * 时间：2020-04-16 08:21:51
   */
  public setSelectedAudioCss(i) {
    this.el.nativeElement.querySelectorAll('tr.audioBody').forEach((element, index) => {
      element.classList.remove('active');
      if (index === i) {
        element.classList.add('active');
      }
    });
  }

  /**
   * 描述：播放控制（递归，循环播放）
   * 作者：oyjl
   * 时间：2020-04-16 08:22:18
   */
  public cyclePlay() {
    this.audioSource = this.audioList[this.index];
    this.isLoadAnimation = true;
    this.ti = setInterval(() => {
      if (this.audioContainer.nativeElement.readyState === 4) {
        if (this.audioContainer.nativeElement.ended || !this.isCycle) { // 如果播放结束或者循环结束就暂停播放
          this.audioContainer.nativeElement.pause();
          if (this.isCycle) {             // 播放结束并且循环播放就递归调用
            if (this.playSort === 'order' && this.index < (this.audioList.length - 1)) { // 如果顺序播放并且当前播放索引小于列表长度
              ++this.index;
            } else if (this.playSort === 'random') { // 如果随机播放就设置播放索引为随机数
              const i = Math.floor(Math.random() * this.audioList.length);
              this.index = i;
            } else if (this.playSort === 'cycle') {
              // 单曲循环，只重新加载资源文件
              this.audioContainer.nativeElement.load();
            } else {
              this.index = 0;
            }
            this.currentLrc = '';
            this.setSelectedAudioCss(this.index);
            this.lrcHandle();
            this.cyclePlay();
          }
        } else if (this.audioContainer.nativeElement.paused) { // 判断音频文件是否暂停，如果暂停，就执行播放
          this.audioContainer.nativeElement.play();
        } else {
          this.currentTime = Math.floor(this.audioContainer.nativeElement.currentTime); // 设置当前播放时间
          if (this.currentTime > 0) {
            this.isLoadAnimation = false;
          }
        }
      }
    }, 1000);
  }

  /**
   * 描述：音乐列表显示/隐藏切换
   * 作者：oyjl
   * 时间：2020-04-16 08:22:43
   */
  public listToggle() {
    this.listShow = !this.listShow;
  }

  /**
   * 描述：修改主题控制
   * 作者：oyjl
   * 时间：2020-04-16 12:25:24
   */
  public changeTheme(color) {
    this.audioMain.nativeElement.style.background = 'linear-gradient(210deg, ' + color + ', transparent)';
  }

}
